package com.tsmti.system.service.impl;


import com.tsmti.core.common.service.impl.BaseServiceImpl;
import com.tsmti.system.entity.User;
import com.tsmti.system.service.UserOrganizationService;
import com.tsmti.system.service.UserRoleService;
import com.tsmti.system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.io.Serializable;
import java.util.List;

/**
 * Title：PimsSystem
 * Class：com.ts.sys.service.impl
 * Comapny:
 *
 * @author：zcw
 * @version：2.5 CreateTime：2018/1/17 16:37
 * Modify log:
 * Description：
 */
@Transactional(rollbackFor = Exception.class)
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User> implements UserService {
    @Autowired
    private PasswordService passwordService;
    @Autowired
    private UserOrganizationService userOrganizationService;
    @Autowired
    private UserRoleService userRoleService;


    @Override
    public void changePassword(long userid, String newPassword) {
        User user = get(userid);
        if (user != null) {
            user.setPassword(newPassword);
            passwordService.encryptPassword(user);
        }
        saveOrUpdate(user);
    }

    @Override
    public User findByUsername(String username) {
        if (StringUtils.isEmpty(username)) {
            return null;
        }
        return get("userName", username);
    }

    @Override
    public User findByEmail(String email) {
        if (StringUtils.isEmpty(email)) {
            return null;
        }
        return get("email", email);
    }

    @Override
    public User findByPhone(String phone) {
        if (StringUtils.isEmpty(phone)) {
            return null;
        }
        return get("phone", phone);
    }

    @Override
    public User save(User user) {
        passwordService.encryptPassword(user);
        return super.save(user);
    }

    @Override
    public void removeById(Serializable id) {
        super.removeById(id);
        // 删除角色关联
        userRoleService.removeAllByProperty("userId", id);
        // 删除部门关联
        userOrganizationService.removeAllByProperty("userId", id);
    }

    @Override
    public void removeAllById(List<?> ids) {
        for (Object id : ids) {
            this.removeById((Serializable) id);
        }
    }
}
